package com.zpp.common.core.utils;

import com.zpp.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Map;

public class JwtUtils {
    /**
     * ⽣成令牌
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }


    /**
     * 从令牌中获取数据
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_KEY));
    }

    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_ID));
    }

    public static String toStr(Object value) {
        if(value == null) {
            return "";
        }
        return value.toString();
    }

    //测试方法
    public static void main(String[] args) {
        String secret = "asdfghjkl";

/*        Map<String,Object> map = new HashMap<>();
        map.put("userId",123456);

        String token = createToken(map, secret);
        System.out.println(token);*/

        String token = "eyJhbGciOiJIUzUxMiJ9." +
                "eyJ1c2VySWQiOjEsInVzZXJLZXkiOiIxN2I4YTM1ZC04MjhhLTRhMDctYmU1ZS02ZThjZTQ3ZjQwOGEifQ." +
                "0gk0z8hV_xbzxjs50y5UNZza9CyCV9P1L_lLR1fIbJK64L3Y44wk7Mkmr-z3JzU9cz4VfTlgxXWqWWzoHagGMQ";

        Claims claims = parseToken(token, secret);
        System.out.println(claims);
    }


}
